package com.realtyManage.springboot.Service.impl;

import com.realtyManage.springboot.Dao.ApplyInfoRepository;
import com.realtyManage.springboot.Dao.ApplyRuleRepository;
import com.realtyManage.springboot.Dao.CustomerRegistrationRepository;
import com.realtyManage.springboot.Model.Do.*;
import com.realtyManage.springboot.Model.Vo.ApplyEntity;
import com.realtyManage.springboot.Service.IApplyInfoService;
import com.realtyManage.springboot.Service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import javax.transaction.Transactional;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * ApplyInfoServiceImpl
 *
 * @Author 杭州素色网络科技有限公司
 * @Date 2019/4/9
 **/
@Service
@Transactional
public class ApplyInfoServiceImpl implements IApplyInfoService {
    @Autowired
    private ApplyInfoRepository applyInfoRepository;

    @Autowired
    private IUserService userService;

    @Autowired
    private ApplyRuleRepository applyRuleRepository;

    @Autowired
    private CustomerRegistrationRepository customerRegistrationRepository;

    @Autowired
    private IApplyInfoService applyInfoService;


    @Override
    public List<ApplyRule> queryApplyRule() {
        return applyRuleRepository.findAll();
    }

    @Override
    public ApplyInfo queryApplyInfo(String xnh) {
        return applyInfoRepository.queryApplyInfo(xnh);
    }

    @Override
    public void scanGq() {
        List<ApplyInfo> lst = applyInfoRepository.queryApplyYGQ(); //查询状态为报备 到访 退房的记录
        ApplyRule ar = applyRuleRepository.queryApplyRule();
        //获取保护天数
        int fqh = ar.getFqhNum();   //非全号保护期
        int qh = ar.getQhNum();   //全号保护期
        int fqd = ar.getFqfNum();   //非全号到访保护期
        for (ApplyInfo applyInfo : lst){
            if (applyInfo.getType() == 0){   //非全号报备   ===》 到访保护期
                Calendar ca = Calendar.getInstance();
                Calendar xa = Calendar.getInstance();
                xa.setTime(new Date());
                ca.setTime(applyInfo.getApplyTime());
                ca.add(Calendar.DATE, fqd); // fqd为设置的非全号报备的到访保护期，超过保护期就进入无效状态
                if(xa.compareTo(ca) > 0 ){
                    if (applyInfo.getStep() == 0){   //报备状态
                        applyInfo.setStep(4); //进入无效报备
                    }
                }
            }
            if (applyInfo.getType() == 0){  //非全号报备 ===》  非全号保护期
                Calendar ca = Calendar.getInstance();
                Calendar xa = Calendar.getInstance();
                xa.setTime(new Date());
                ca.setTime(applyInfo.getApplyTime());
                ca.add(Calendar.DATE, fqh); // fqh为设置的非全号报备的保护期，超过保护期就进入无效状态
                if (xa.compareTo(ca) > 0){
                    if (applyInfo.getStep() == 0 || applyInfo.getStep() == 1){  //报备和到访会进入无效
                        applyInfo.setStep(4);
                    }
                }
            }else if (applyInfo.getType() == 1){  //全号报备
                Calendar ca = Calendar.getInstance();
                Calendar xa = Calendar.getInstance();
                xa.setTime(new Date());
                ca.setTime(applyInfo.getApplyTime());
                ca.add(Calendar.DATE, qh); // qh为设置的全号报备的保护期，超过保护期没有成交就进入无效状态
                if (xa.compareTo(ca) > 0){
                    int count = customerRegistrationRepository.queryQH(applyInfo.getCustomerPhone());
                    if (count < 1){  //说明没有成交
                        applyInfo.setStep(4);
                    }
                }
            }
        }
        /*if (lst.size() > 0){
            for (ApplyInfo applyInfo : lst){
                Calendar ca = Calendar.getInstance();
                Calendar xa = Calendar.getInstance();
                xa.setTime(new Date());
                ca.setTime(applyInfo.getApplyTime());
              //  ca.add(Calendar.DATE, b);// b为增加的天数，可以改变的
                if(xa.compareTo(ca) >= 0 ){
                    if (applyInfo.getState() == 0){   //无效用户
                        applyInfo.setStep(4); //进入无效用户
                    }
                }
            }
        }*/
    }

    @Override
    public void updateStep(String virtualNumber) {
        //查询最新关联经济人
        System.out.println("========================================这是华丽的显现================================================>"+virtualNumber);
        Integer id = applyInfoRepository.queryId(virtualNumber);
        if (id != null){
            ApplyInfo ai = new ApplyInfo();
            ai.setId(id);
            ai.setStep(3);
            applyInfoRepository.updateApplyInfo(ai);
        }
    }

    @Override
    public void updateTStep(String virtualNumber) {
        //查询最新关联经济人
        Integer id = applyInfoRepository.queryId(virtualNumber);
        if (id != null){
            ApplyInfo ai = new ApplyInfo();
            ai.setId(id);
            ai.setStep(5);
            applyInfoRepository.updateApplyInfo(ai);
        }
    }

    @Override
    public void updateJJStep(String virtualNumber) {
        //查询最新关联经济人
        Integer id = applyInfoRepository.queryId(virtualNumber);
        if (id != null){
            ApplyInfo ai = new ApplyInfo();
            ai.setId(id);
            ai.setStep(4);
            applyInfoRepository.updateApplyInfo(ai);
        }
    }

    @Override
    public List<ApplyInfo> queryApplyDetailById(String id) {
        List<ApplyInfo> lst = applyInfoRepository.queryApplyDetailById(id);
        if (lst.size() > 0){
            for (ApplyInfo applyInfo : lst){
                ApplyRule ar = applyRuleRepository.queryApplyRule();
                int fqd = ar.getFqfNum();   //非全号到访保护期
                if (applyInfo.getType() == 0){   //非全号报备   ===》 到访保护期
                    Calendar ca = Calendar.getInstance();
                    ca.setTime(applyInfo.getApplyTime());
                    ca.add(Calendar.DATE, fqd); // fqd为设置的非全号报备的到访保护期，超过保护期就进入无效状态
                    applyInfo.setRestTime(ca.getTime());
                }
            }
        }
        return lst;
    }

    @Override
    public int updateApplyRule(ApplyRule applyRule) {
        return applyRuleRepository.updateApplyRule(applyRule);
    }

    @Override
    public int addApplyInfo(ApplyInfo applyInfo) {
        return applyInfoRepository.save(applyInfo).getId();
    }

    @Override
    public List<ApplyInfo> queryApplyInfoS(ApplyEntity applyEntity) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ApplyRule ar = applyRuleRepository.queryApplyRule();
        //获取保护天数
        int fqh = ar.getFqhNum();   //非全号保护期
        int qh = ar.getQhNum();   //全号保护期
        int fqd = ar.getFqfNum();   //非全号到访保护期
        //动态查询条件
        Specification<ApplyInfo> specification = (Specification<ApplyInfo>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            // 根据用户名或手机号List 查询
            List<Predicate> usernameOrPhonePredicate = new ArrayList<>();
            if (applyEntity.getCustomerName() != null) {
                usernameOrPhonePredicate.add(criteriaBuilder.like(root.get("customerName"), "%" + applyEntity.getCustomerName() + "%"));
                usernameOrPhonePredicate.add(criteriaBuilder.like(root.get("customerPhone"),"%" + applyEntity.getCustomerName() + "%"));
                list.add(criteriaBuilder.or(usernameOrPhonePredicate.toArray(new Predicate[0])));
            }
            Predicate p2 = criteriaBuilder.equal(root.get("userId"), applyEntity.getUserId());
            list.add(p2);
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        List<ApplyInfo> lst = applyInfoRepository.findAll(specification);
        for (ApplyInfo applyInfo : lst){
            if (applyInfo.getType() == 0){   //非全号报备   ===》 到访保护期
                Calendar ca = Calendar.getInstance();
                Calendar xa = Calendar.getInstance();
                xa.setTime(new Date());
                ca.setTime(applyInfo.getApplyTime());
                ca.add(Calendar.DATE, fqd); // fqd为设置的非全号报备的到访保护期，超过保护期就进入无效状态
                if(xa.compareTo(ca) > 0 ){
                    if (applyInfo.getStep() == 0){   //报备状态
                        applyInfo.setStep(4); //进入无效报备
                    }
                }
            }
            if (applyInfo.getType() == 0){  //非全号报备 ===》  非全号保护期
                Calendar ca = Calendar.getInstance();
                Calendar xa = Calendar.getInstance();
                xa.setTime(new Date());
                ca.setTime(applyInfo.getApplyTime());
                ca.add(Calendar.DATE, fqh); // fqh为设置的非全号报备的保护期，超过保护期就进入无效状态
                if (xa.compareTo(ca) > 0){
                    if (applyInfo.getStep() == 0 || applyInfo.getStep() == 1){  //报备和到访会进入无效
                        applyInfo.setStep(4);
                    }
                }
            }else if (applyInfo.getType() == 1){  //全号报备
                Calendar ca = Calendar.getInstance();
                Calendar xa = Calendar.getInstance();
                xa.setTime(new Date());
                ca.setTime(applyInfo.getApplyTime());
                ca.add(Calendar.DATE, qh); // qh为设置的全号报备的保护期，超过保护期没有成交就进入无效状态
                if (xa.compareTo(ca) > 0){
                    int count = customerRegistrationRepository.queryQH(applyInfo.getCustomerPhone());
                    if (count < 1){  //说明没有成交
                        applyInfo.setStep(4);
                    }
                }
            }
        }
        return lst;
    }

    @Override
    public List<ApplyInfo> queryApplyInfoE(ApplyEntity applyEntity) {
        //动态查询条件
        Specification<ApplyInfo> specification = (Specification<ApplyInfo>) (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            // 根据用户名或手机号List 查询
            List<Predicate> usernameOrPhonePredicate = new ArrayList<>();
            if (applyEntity.getCustomerName() != null) {
                usernameOrPhonePredicate.add(criteriaBuilder.like(root.get("customerName"), "%" + applyEntity.getCustomerName() + "%"));
                usernameOrPhonePredicate.add(criteriaBuilder.like(root.get("customerPhone"),"%" + applyEntity.getCustomerName() + "%"));
                list.add(criteriaBuilder.or(usernameOrPhonePredicate.toArray(new Predicate[0])));
            }
            if (applyEntity.getType() != null) {  //根据状态查询 0报备  1到访  2大定 3结佣 4无效 5退房
                Predicate p1 = criteriaBuilder.equal(root.get("step"), applyEntity.getType());
                list.add(p1);
            }

            Predicate p2 = criteriaBuilder.equal(root.get("userId"), applyEntity.getUserId());
            list.add(p2);
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        List<ApplyInfo> lst = applyInfoRepository.findAll(specification);
        //报备到访时间
        if (lst.size() > 0){
            for (ApplyInfo applyInfo : lst){
                ApplyRule ar = applyRuleRepository.queryApplyRule();
                int fqd = ar.getFqfNum();   //非全号到访保护期
                int fqh = ar.getFqhNum();   //非全号到访保护期
                int qh = ar.getQhNum();  //全号保护期
               // if (applyInfo.getType() == 0){   //非全号报备   ===》 到访保护期
                    Calendar ca = Calendar.getInstance();
                    ca.setTime(applyInfo.getApplyTime());
                    if (applyInfo.getStep() == 0){
                        ca.add(Calendar.DATE, fqd); // fqd为设置的非全号报备的到访保护期，超过保护期就进入无效状态
                    }else if (applyInfo.getStep() == 1 && applyInfo.getType() == 0){
                        ca.add(Calendar.DATE, fqh);
                    }else if (applyInfo.getType() == 1){
                        ca.add(Calendar.DATE, qh);
                    }
                    applyInfo.setRestTime(ca.getTime());
              //  }
            }
        }
        return lst;
    }

   /* @Override
    public int queryApplyRuleByType(Integer b) {
        return applyRuleRepository.queryApplyRuleByType(b);
    }*/

    @Override
    public int verification(int userId, String phone) {
        int uCount = applyInfoRepository.verification(userId,phone);
        if (uCount > 0){
            return 2;    //本人已经报备
        }else if (uCount == 0){
            int yCount = applyInfoRepository.verification(phone);
            if (yCount > 0){
                return  4;   //别人已经报备
            }else if(yCount == 0){
                int allCount = customerRegistrationRepository.countPhone(phone);
                if (allCount > 0){
                    return  8; //已经存在客户
                }
            }
        }
        return 0;
    }

    @Override
    public int confirmVisit(ApplyInfo applyInfo) {
        return applyInfoRepository.updateApplyInfo(applyInfo);
    }

    @Override
    public List<ApplyInfo> scanRecord(Integer uid) {
        return applyInfoRepository.scanRecord(uid);
    }


    @Override
    public Page<ApplyInfo> queryApplyInfoAll(ApplyEntity applyEntity) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Integer pageNumber = applyEntity.getPageNumber()-1;
        Integer pageSize = applyEntity.getPageSize();
        Integer i = 0;
        // 排序条件 默认最新
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(pageNumber,pageSize,sort);
        //动态查询条件
        Specification<ApplyInfo> specification = (Specification<ApplyInfo>)(root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            List<Predicate> usernameOrPhonePredicate = new ArrayList<>();
            if (applyEntity.getCustomerName() != null) {
                usernameOrPhonePredicate.add(criteriaBuilder.like(root.get("customerName"), "%" + applyEntity.getCustomerName() + "%"));
                usernameOrPhonePredicate.add(criteriaBuilder.like(root.get("customerPhone"),"%" + applyEntity.getCustomerName() + "%"));
                list.add(criteriaBuilder.or(usernameOrPhonePredicate.toArray(new Predicate[0])));
            }
            if (applyEntity.getType() != null) {  //根据状态查询 0报备  1到访  2大定 3结佣 4无效 5退房
                Predicate p1 = criteriaBuilder.equal(root.get("step"), applyEntity.getType());
                list.add(p1);
            }
            return criteriaBuilder.and(list.toArray(new Predicate[0]));
        };
        Page<ApplyInfo> lst = applyInfoRepository.findAll(specification, pageable);
        //报备到访时间
        if (lst.getContent().size() > 0){
            for (ApplyInfo applyInfo : lst){
                ApplyRule ar = applyRuleRepository.queryApplyRule();
                int fqd = ar.getFqfNum();   //非全号到访保护期
                int fqh = ar.getFqhNum();   //非全号到访保护期
                int qh = ar.getQhNum();  //全号保护期
                if (applyInfo.getType() == 0){   //非全号报备   ===》 到访保护期
                    Calendar ca = Calendar.getInstance();
                    ca.setTime(applyInfo.getApplyTime());
                    if (applyInfo.getStep() == 0){
                        ca.add(Calendar.DATE, fqd); // fqd为设置的非全号报备的到访保护期，超过保护期就进入无效状态
                    }else if (applyInfo.getStep() == 1 && applyInfo.getType() == 0){
                        ca.add(Calendar.DATE, fqh);
                    }else if (applyInfo.getType() == 1){
                        ca.add(Calendar.DATE, qh);
                    }
                    applyInfo.setRestTime(ca.getTime());
                }
            }
        }
        return lst;
    }

    @Override
    public int deleteInvalidApply(String id) {
        return applyInfoRepository.deleteInvalidApply(id);
    }

}
